package com.zhongpengcheng.blog.auth.filter;

import cn.hutool.core.lang.Snowflake;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * traceId生成Filter
 * <br>traceId为 <strong>0000000000000000000</strong> 时表示为system log
 *
 * @author ZhongPengCheng
 * @version 1.0
 * @date 2021-08-20 23:38:00
 */
@Slf4j
@WebFilter(filterName = "traceIdFilter", urlPatterns = "/*")
@Component
@Order(0)
public class TraceIdFilter implements Filter {

    private Snowflake snowflake;

    public static final String TRACE_ID = "TRACE_ID";

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws
            IOException, ServletException {
        MDC.put(TRACE_ID, snowflake.nextIdStr());
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        MDC.clear();
    }

    @Autowired
    public TraceIdFilter setSnowflake(@Qualifier("traceIdGenerator") Snowflake snowflake) {
        this.snowflake = snowflake;
        return this;
    }
}
